package gz.metro.datasync.service;

import gz.metro.datasync.entity.form.*;
import gz.metro.datasync.utils.DateHelper;
import gz.metro.datasync.utils.RequestParam;
import gz.metro.datasync.utils.Result;
import com.alibaba.fastjson.JSONObject;
import gz.metro.datasync.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author feily
 * @功能描述  数据业务客户端服务类
 * @创建时间 2018-07-31 20:03:10
 */
@Slf4j
@Service
public class DataClientService {

	public static final String MESSAGE_PARAM_APP_TOKEN_NULL = "参数【appToken】不能为空";

	/**
	 * 服务请求路径
	 */
	protected String serverPath;

	/**
	 * 应用身份标识
	 */
	protected String appToken;


	/**
	 * 增量获取组织信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public Result<List<OrgDataForm>> queryOrgs(RequestParam requestParam) {
		log.info("queryOrgs");
		log.info("requestParam:{}", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		Result<List<OrgDataForm>> resultEntity = new Result<List<OrgDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<OrgDataForm> orgs = new ArrayList<OrgDataForm>();
			
			String url = this.buildUrl("queryOrgs", updateBeginDate, updateEndDate);
			Result<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}

			String businessObject = resultContent.getBusinessObject();
			List<OrgDataForm> arrayMenus = JSONObject.parseArray(businessObject, OrgDataForm.class);
			for(OrgDataForm orgDataForm:arrayMenus){
				orgs.add(orgDataForm);
			}

			resultEntity.setBusinessObject(orgs);

		} catch (Exception ex) {
			log.info("获取组织信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * 增量获取用户信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public Result<List<UserDataForm>> queryUsers(RequestParam requestParam) {
		log.info("queryUsers");
		log.info("requestParam:{}", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		Result<List<UserDataForm>> resultEntity = new Result<List<UserDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<UserDataForm> users = new ArrayList<UserDataForm>();
			String url = this.buildUrl("queryUsers", updateBeginDate, updateEndDate);
			Result<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}
			String businessObject = resultContent.getBusinessObject();
			List<UserDataForm> arrayMenus = JSONObject.parseArray(businessObject, UserDataForm.class);

			for(UserDataForm userDataForm:arrayMenus){
				users.add(userDataForm);
			}
			resultEntity.setBusinessObject(users);

		} catch (Exception ex) {
			log.error("获取用户信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * http get 请求
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	protected Result<String> requestGet(String url) throws IOException, ClientProtocolException {
		log.info("requestGet");
		log.info("url", url);

		Result<String> resultEntity = new Result<String>();
		CloseableHttpClient client = HttpClientBuilder.create().build();
		CloseableHttpResponse response = client.execute(new HttpGet(url));
		String bodyAsString = EntityUtils.toString(response.getEntity());
		resultEntity.setBusinessObject(bodyAsString);
		resultEntity.setSuccess(response.getStatusLine().getStatusCode() == 200);
		return resultEntity;
	}

	/**
	 * 验证参数
	 * @return
	 */
	protected Result validateParams() {
		Result result = new Result();

		if(StringUtils.isBlank(this.getAppToken())){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_APP_TOKEN_NULL);
			return result;
		}

		return result;
	}

	/**
	 * 构建请求服务路径
	 * @param serviceName
	 * @return
	 */
	protected String buildUrl(String serviceName) {
		String url = serverPath + "/data/{0}?cwAppToken={1}"; //v2版本uuap接口
		url = StringUtils.format(url, serviceName, appToken);
		return url;
	}

	/**
	 * 构建请求服务路径
	 * @param serviceName
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	protected String buildUrl(String serviceName, Date beginDate, Date endDate) throws UnsupportedEncodingException {

		String url = this.buildUrl(serviceName);
		url = url + "&updateBeginDate={0}&updateEndDate={1}";
		url = StringUtils.format(url, DateHelper.formatDate(beginDate), DateHelper.formatDate(endDate));
		return url;
	}

	public String getServerPath() {
		return serverPath;
	}

	public void setServerPath(String serverPath) {
		this.serverPath = serverPath;
	}

	public String getAppToken() {
		return appToken;
	}

	public void setAppToken(String appToken) {
		this.appToken = appToken;
	}

}
